package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    GraphInfoService graphInfoService;

    @Autowired
    ApartmentFacilityService apartmentFacilityService;

    @Autowired
    ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    ApartmentLabelService apartmentLabelService;

    @Autowired
    ProvinceInfoService provinceInfoService;

    @Autowired
    CityInfoService cityInfoService;

    @Autowired
    DistrictInfoService districtInfoService;

    @Autowired
    ApartmentInfoMapper apartmentInfoMapper;


    @Autowired
    GraphInfoMapper graphInfoMapper;

    @Autowired
    FacilityInfoMapper facilityInfoMapper;

    @Autowired
    LabelInfoMapper labelInfoMapper;

    @Autowired
    FeeValueMapper feeValueMapper;


    @Autowired
    ApartmentFacilityMapper apartmentFacilityMapper;

    @Autowired
    ApartmentLabelMapper apartmentLabelMapper;

    @Autowired
    ApartmentFeeValueMapper apartmentFeeValueMapper;

    @Autowired
    RoomInfoMapper roomInfoMapper;

    //开发思路：  修改功能涉及到的多对多关系数据，采用删除旧关系，直接保存新关系。
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        //保存或修改： 如何判断是做保存还是修改

        //只需要判断vo对象中是否存在id值，id值在做修改；不在做保存。
        Long id = apartmentSubmitVo.getId();

        if (id != null) { //----修改----
            //删除公寓和图片的关系
            LambdaQueryWrapper<GraphInfo> queryWrapper = new LambdaQueryWrapper<GraphInfo>();
            queryWrapper.eq(GraphInfo::getItemId, id);
            queryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT); // TypeHandler     @EnumValue
            graphInfoService.remove(queryWrapper);

            //删除公寓和配套之间关系
            LambdaQueryWrapper<ApartmentFacility> facilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            facilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
            apartmentFacilityService.remove(facilityLambdaQueryWrapper);

            //删除公寓和杂费之间关系
            LambdaQueryWrapper<ApartmentFeeValue> feeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            feeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
            apartmentFeeValueService.remove(feeValueLambdaQueryWrapper);

            //删除公寓和标签之间关系
            LambdaQueryWrapper<ApartmentLabel> labelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            labelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
            apartmentLabelService.remove(labelLambdaQueryWrapper);
        }

        //----添加、修改----
        //表单只提交了省市区的id,没有提交名称。需要业务层处理一下。
        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());

        //1.保存公寓数据
        //主键回填： 实体对象保存前id是null。保存后，mybatis框架会把数据库分配的主键值获取到，封装到实体对象中。
        super.saveOrUpdate(apartmentSubmitVo); //对主表数据进行保存或更新。  由于vo对象继承实体对象，所以能够识别对哪张表操作。
        id = apartmentSubmitVo.getId();

        //2.保存图片数据
        //将集合迭代处理，将GraphVo转换实体对象进行保存或更新。
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfoList = new ArrayList<>();
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(id);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList); //批量保存，效率比循环保存效率高。
        }
        //3.保存公寓配套
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<ApartmentFacility> apartmentFacilityList = new ArrayList<>();
            for (Long facilityInfoId : facilityInfoIds) {

                /*ApartmentFacility apartmentFacility = new ApartmentFacility();
                apartmentFacility.setApartmentId(id);
                apartmentFacility.setFacilityId(facilityInfoId);*/

                ApartmentFacility apartmentFacility =
                        ApartmentFacility.builder()
                                .apartmentId(id)
                                .facilityId(facilityInfoId)
                                .build();

                apartmentFacilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }

        //4.保存公寓标签
        List<Long> labelIdList = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIdList)) {
            List<ApartmentLabel> list = new ArrayList<>();
            for (Long labelId : labelIdList) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(id)
                        .labelId(labelId)
                        .build();
                list.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(list);
        }


        //5.保存公寓杂费
        List<Long> feeValueIdList = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIdList)) {
            List<ApartmentFeeValue> list = new ArrayList<>();
            for (Long feeValueId : feeValueIdList) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(id)
                        .feeValueId(feeValueId)
                        .build();
                list.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(list);
        }
    }

    @Override
    public IPage<ApartmentItemVo> pageQuery(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageQuery(page,queryVo);
    }


    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        //1.查询主表数据
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(id);
        if(apartmentInfo==null){
            return null;
        }

        ApartmentDetailVo vo = new ApartmentDetailVo();
        //类型转换，属性对拷
        BeanUtils.copyProperties(apartmentInfo,vo);

        //2.查询关联表数据 - 图片
        List<GraphVo> graphVoList = graphInfoMapper.selectListByApartmentId(ItemType.APARTMENT,id);

        //3.查询关联表数据 - 公寓配套
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);

        //4.查询关联表数据 - 公寓标签
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);

        //5.查询关联表数据 - 公寓杂费
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);

        //封装关联数据
        vo.setGraphVoList(graphVoList);
        vo.setFacilityInfoList(facilityInfoList);
        vo.setLabelInfoList(labelInfoList);
        vo.setFeeValueVoList(feeValueVoList);

        //返回封装好的数据
        return vo;
    }


    @Override
    public void removeApartmentById(Long id) {
        //0.删除公寓时，判断是否存在房间。有房间存在不能删除，给与错误提示消息。
        Long count = roomInfoMapper.selectCount(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, id));
        if(count>0){
            //throw new RuntimeException("公寓下有房间不允许删除");
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        //1.删除主表数据
        super.removeById(id);

        //2.删除公寓关联图片数据
        graphInfoMapper.delete(new LambdaQueryWrapper<GraphInfo>()
                .eq(GraphInfo::getItemType,ItemType.APARTMENT)
                .eq(GraphInfo::getItemId,id));

        //3.删除公寓和配套关联数据
        apartmentFacilityMapper.delete(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,id));

        //4.删除公寓和标签关联数据
        apartmentLabelMapper.delete(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,id));

        //5.删除公寓和杂费关联数据
        apartmentFeeValueMapper.delete(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,id));
    }
}




